package org.bonorsoft.modules.system.aspect;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.bonorsoft.common.aspect.annotation.PermissionData;
import org.bonorsoft.common.constant.CommonConstant;
import org.bonorsoft.common.system.util.JwtUtil;
import org.bonorsoft.common.system.util.WilliamDataAutorUtils;
import org.bonorsoft.common.system.vo.LoginDingUser;
import org.bonorsoft.common.util.SpringContextUtils;
import org.bonorsoft.common.util.StringUtils;
import org.bonorsoft.common.util.oConvertUtils;
import org.bonorsoft.modules.dingding.entity.SysRole;
import org.bonorsoft.modules.dingding.service.ISysRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
  * 数据权限切面处理类
  *  当被请求的方法有注解PermissionData时,会在往当前request中写入数据权限信息
 * @Date 2019年4月10日
 * @Version: 1.0
 */
@Aspect
@Component
@Slf4j
public class PermissionDataAspect {

	/**
	 * 全部数据权限
	 */
	public static final String DATA_SCOPE_ALL = "1";

	/**
	 * 自定数据权限
	 */
	public static final String DATA_SCOPE_CUSTOM = "2";

	/**
	 * 部门数据权限
	 */
	public static final String DATA_SCOPE_DEPT = "3";

	/**
	 * 部门及以下数据权限
	 */
	public static final String DATA_SCOPE_DEPT_AND_CHILD = "4";

	/**
	 * 仅本人数据权限
	 */
	public static final String DATA_SCOPE_SELF = "5";

	@Autowired
	private ISysRoleService roleService;

	@Pointcut("@annotation(org.bonorsoft.common.aspect.annotation.PermissionData)")
	public void pointCut() {
		
	}
	
	@Around("pointCut()")
	public Object arround(ProceedingJoinPoint point) throws  Throwable{

		// 获取当前的用户
		LoginDingUser user = (LoginDingUser) SecurityUtils.getSubject().getPrincipal();
		if (user != null)
		{
			// 如果是超级管理员，则不过滤数据 !user.isAdmin()
			if (!user.isAdmin())
			{
				HttpServletRequest request = SpringContextUtils.getHttpServletRequest();
				MethodSignature signature = (MethodSignature) point.getSignature();
				Method method = signature.getMethod();
				PermissionData pd = method.getAnnotation(PermissionData.class);
				String value = pd.value();
				String userAlias = pd.userAlias();
				String deptAlias = pd.deptAlias();
				StringBuilder sqlString = new StringBuilder();
				List<SysRole> sysRoles = roleService.getRolesByUserId(user.getUserid());

				if(value.equals(CommonConstant.SINGLE_TYPE)){
					//构造器拼接queryWrapper
					log.info("构造器拼接queryWrapper");
					sysRoles.forEach(role -> {
						String dataScope = role.getDataScope();
						if (DATA_SCOPE_CUSTOM.equals(dataScope))
						{
							sqlString.append(StringUtils.format(
									" OR dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", role.getId()));
						}
						else if (DATA_SCOPE_DEPT.equals(dataScope))
						{
							sqlString.append(StringUtils.format(" OR dept_id = {} ", user.getDeptId()));
						}
						else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
						{
							sqlString.append(StringUtils.format(
									" OR dept_id IN ( SELECT dept_id FROM sys_depart WHERE dept_id = {} or instr(','||ancestors||',',','||{}||',')<>0 )",
									 user.getDeptId(), user.getDeptId()));
						}
						else if (DATA_SCOPE_SELF.equals(dataScope))
						{
							if (StringUtils.isNotBlank(userAlias))
							{
								sqlString.append(StringUtils.format(" OR user_id = {} ", user.getUserid()));
							}
							else
							{
								// 数据权限为仅本人且没有userAlias别名不查询任何数据
								sqlString.append(" OR 1=0 ");
							}
						}

					});
				} else {
					//
					log.info("xml拼接sql语句");
					sysRoles.forEach(role -> {
						String dataScope = role.getDataScope();
						if (DATA_SCOPE_CUSTOM.equals(dataScope))
						{
							sqlString.append(StringUtils.format(
									" OR {}.dept_id IN ( SELECT dept_id FROM sys_role_dept WHERE role_id = {} ) ", deptAlias,
									role.getId()));
						}
						else if (DATA_SCOPE_DEPT.equals(dataScope))
						{
							sqlString.append(StringUtils.format(" OR {}.dept_id = {} ", deptAlias, user.getDeptId()));
						}
						else if (DATA_SCOPE_DEPT_AND_CHILD.equals(dataScope))
						{
							sqlString.append(StringUtils.format(
									" OR {}.dept_id IN ( SELECT dept_id FROM sys_depart WHERE dept_id = {} or instr(','||ancestors||',',','||{}||',')<>0 )",
									deptAlias, user.getDeptId(), user.getDeptId()));
						}
						else if (DATA_SCOPE_SELF.equals(dataScope))
						{
							if (StringUtils.isNotBlank(userAlias))
							{
								sqlString.append(StringUtils.format(" OR {}.user_id = {} ", userAlias, user.getUserid()));
							}
							else
							{
								// 数据权限为仅本人且没有userAlias别名不查询任何数据
								sqlString.append(" OR 1=0 ");
							}
						}

					});
				}

				if (StringUtils.isNotBlank(sqlString.toString()))
				{
					WilliamDataAutorUtils.installSearchConditon(request, sqlString.substring(4));
				}
			}
		}
		return  point.proceed();
	}

	
}
